package filter;

import dto.StatusDto;
import pojo.Merchant;
import util.HttpUtil;
import util.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by CHENCO7 on 7/29/2017.
 */
public class VerifyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Merchant merchant = (Merchant) req.getSession().getAttribute("user");
        String name = merchant.getName();
        StatusDto statusDto = new StatusDto();
        try {
            String status = HttpUtil.getResponseStr("/admins/m/status/get?name=" + name);
            System.out.println("status == " + status);
            statusDto = (StatusDto) JsonUtil.toJsonObject(status, StatusDto.class);
        } catch (Exception e) {
            PrintWriter writer = resp.getWriter();
            writer.write("http error!");
        }

        if (StatusDto.WHITE_LIST.equals(statusDto.getStatus())) {
            chain.doFilter(request, response);
        } else if (StatusDto.WAIT_AUDIT.equals(statusDto.getStatus()) || StatusDto.BLACK_LIST.equals(statusDto.getStatus())) {
            req.setAttribute("statusInfo", statusDto.getStatus());
            req.getRequestDispatcher("/WEB-INF/sec/refresh.jsp").forward(req, resp);
        } else if (StatusDto.REJECT.equals(statusDto.getStatus())){
            req.setAttribute("statusInfo", statusDto.getStatus());
            req.setAttribute("message", statusDto.getMessage());
            req.getRequestDispatcher("/WEB-INF/sec/refresh.jsp").forward(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
